var $personalData = $("#personalData");
define(["allTpl"],function(template){
	return {
		"init" :function(){
			//获取个人信息
	        $.ajax({
	            url: _CONFIG[__webState].AJAX_URL+ "api/UserMainInfo/GetUserInfo",
	            type: "post",
	            dataType: "json",
	            success: function (data) {
	            	if(data.Code == 0){
	                	getPersonalData(data.Data,template);
	                	
	            	}else{
	            		popWrap.open({content:data.Message,autoClose:false});
	            	}
	            }
	        }).fail(
	        function (xhr, textStatus, err) {
	            popWrap.open({content:"数据获取失败",autoClose:false});
	        }).always(function(){
	        	ajaxLoading.remove();
	        });
		}
	}
});
function getPersonalData(data,template){
	var html = ['<div class="top">',
			'<dl>',
				'<dt>万里行积分</dt>',
				'<dd>'+data.MobilePhone+'</dd>',
			'</dl>',
		'</div>',
		'<div class="routine">',
			(function(d){
				var h = "";
				if(d){
					h+='<dl>'+
						'<dt>会员邮箱</dt>'+
						'<dd><b>'+data.Email+'</b></dd>'+
					'</dl>';
				};
				return h;
			})(data.Email),
			'<dl>',
				'<dt>会员手机号</dt>',
				'<dd><b>'+data.MobilePhone+'</b></dd>',
			'</dl>',
			'<dl>',
				'<dt>常旅客卡号</dt>',
				'<dd><b>'+data.ChangPassengerCard+'</b></dd>',
			'</dl>',
			'<dl id="address_fillOrderPage" data-target="address">',
				'<dt>收货地址</dt>',
				'<dd><b></b><em></em></dd>',
			'</dl>',
		'</div>'];
	$personalData.html(html.join(''));	
	g_address(template)
}


//地址列表选择
function g_address(template){
	console.log($("#address_fillOrderPage").html())
    $("#address_fillOrderPage").CutScreen({template:true,isHead:false,init:function($dom){
        var _this = this;
         //地址列表
        function getList(){
            $.ajax({
              url:_CONFIG[__webState].AJAX_URL+ "api/UserReceivingList/GetReceivingList",
              type: "post",
              dataType: "json",
              beforeSend:function(){
                ajaxLoading.open({target:$dom});
              },
              data:{
                  pageIndex: 1,
                  pageSize:20
              }
            }).done(function(data){
                if(data.Code == 0){
                    $dom.html(template('Reservation/common/address', data.Data));
                    $(".left",$dom).on("click",function(e){
                        var _addObj = JSON.parse($(this).parents("dl").find(".edit").attr("data-address")),
                            $contactInfo = $("#contactInfo");
                            console.log(_addObj)
                        if(e.target.className !="setDefault"){
                            _this.back($(this));
                            var temp = '<div class="ld">'+
                                '<p class="info">'+
                                    '<span></span>'+
                                    '<span class="name">'+_addObj.ReceivingName+'</span>'+
                                    '<span class="phone">'+_addObj.MobilePhone+'</span>'+
                                '</p>'+
                                '<p class="address">'+_addObj.ProvinceName+_addObj.CityName+_addObj.DistrictName+_addObj.CompleteAddress
                                    '<span class="ico">默认</span> '+
                                '</p>'+
                            '</div>'+
                            '<div class="icon-next">&#xe91f</div> ';
                            $contactInfo.html(temp);
                        }
                    });
                    //设置默认地址
                    $(".setDefault",$dom).on("click",function(e){
                        var _this = $(this);
                            id = _this.attr("data-id"),
                            parent = _this.parents("dl");
                        $.ajax({
                            url: _CONFIG[__webState].AJAX_URL+ "/api/UserReceivingList/SettingDefault",
                            type: "post",
                            dataType: "json",
                            beforeSend:function(){
                                popWrap.alert({content:"正在设置",autoClose:false});
                            },
                            data:{
                                sysNo:id
                            }
                        }).done(function(data){
                            popWrap.alertRemove();
                            popWrap.alert({content:"设置成功",confirm:function(){
                                getList();
                            }});
                        }).fail(function (xhr, textStatus, err) {
                            popWrap.alert({content:"设置失败"});
                        });
                    });
					//删除地址
					$(".delete",$dom).on("click",function(e){
                        var _this = $(this);
                            id = _this.attr("data-id"),
                            parent = _this.parents("dl");
                        popWrap.defult({title:"警告",content:"是否确定删除该地址",confirm:function(){
	                        $.ajax({
	                            url: _CONFIG[__webState].AJAX_URL+ "/api/UserReceivingList/DeleteReceiving",
	                            type: "post",
	                            dataType: "json",
	                            beforeSend:function(){
	                                popWrap.alert({content:"正在删除",autoClose:false});
	                            },
	                            data:{
	                                sysNo:id
	                            }
	                        }).done(function(data){
	                            popWrap.alertRemove();
	                            popWrap.alert({content:"删除成功",confirm:function(){
	                                getList();
	                            }});
	                        }).fail(function (xhr, textStatus, err) {
	                            popWrap.alert({content:"删除失败"});
	                        });
                        }})    
                    });
					//最多10条记录
					$(".btnOrange.disabled").on("click",function(){
						popWrap.alert({content:"最多10条记录",autoClose:800})
					});
                    //新增加地址
                    $("#add_address,.edit",$dom).CutScreen({template:true,isHead:false,init:function($dom2,that){
                        var _this_ = this;
                        var _that_ = $(this);
                        var _obj_ = (that.attr("data-address"));
                        typeof _obj_ === "undefined" ? _obj_ = {"ReceivingName":"" } : _obj_ = JSON.parse(_obj_);
                        $dom2.append(template('Reservation/common/add_address',_obj_));
                        var $Province = $("select[name=Province]",$dom2),
                            $City = $("select[name=City]",$dom2),
                            $County = $("select[name=County]",$dom2),
                            $addressee = $("input[name=addressee]"),
                            $mobile = $("input[name=mobile]"),
                            $addressDetails = $("textarea[name=addressDetails]"),
                            ProvinceData =[],
                            CityData =[],
                            CountyData =[];
                        //获取省份  
                        var ProvinceId = $Province.prop("id");
                        var CityId = $City.prop("id");
                        var CountyId = $County.prop("id");
                        $.ajax({
                              url: _CONFIG[__webState].AJAX_URL+"/api/BaseData/GetProvince",
                              type: "post",
                              async:false,
                              dataType: "json"
                        }).done(function(data){
                            if(data.Code == 0){
                                $.each(data.Data, function(v,k) {
                                    ProvinceData.push("<option value='"+k.SysNo+"'>"+k.ProvinceName+"</option>");
                                });
                                $Province.append(ProvinceData.join(''));
                            }
                        }).fail(function (xhr, textStatus, err) {
                            popWrap.alert({content:"省份获取失败",autoClose:false});
                        });
                        if(ProvinceId)
                        $("option[value="+ProvinceId+"]",$Province).attr("selected",true);
                        //获取城市
                        $Province.on("change",function(){
                            $.ajax({
                                  url: _CONFIG[__webState].AJAX_URL+"/api/BaseData/GetCityList",
                                  type: "post",
                                  async:false,
                                  data:{
                                    sysNo :$Province.val()
                                  },
                                  dataType: "json"
                            }).done(function(data){
                                if(data.Code == 0){
                                    CityData = [];
                                    $.each(data.Data, function(v,k) {
                                        CityData.push("<option value='"+k.SysNo+"'>"+k.CityName+"</option>");
                                    });
                                    $City.html(CityData.join('')).trigger("change");
                                    $City.prepend("<option value=''>请选择区县</option>")
                                    $County.html("<option value=''>请选择区县</option>")
                                }
                            }).fail(function (xhr, textStatus, err) {
                                popWrap.alert({content:"省份获取失败",autoClose:false});
                            });
                        });
                        $Province.trigger("change");
                        if(CityId)
                        $("option[value="+CityId+"]",$City).attr("selected",true);
                        //获取区县
                        $City.on("change",function(){
                            $.ajax({
                                  url: _CONFIG[__webState].AJAX_URL+"/api/BaseData/GetDistrict",
                                  type: "post",
                                  async:false,
                                  data:{
                                    sysNo :$Province.val()
                                  },
                                  dataType: "json"
                            }).done(function(data){
                                if(data.Code == 0){
                                    CountyData = [];
                                    $.each(data.Data, function(v,k) {
                                        CountyData.push("<option value='"+k.SysNo+"'>"+k.DistrictName+"</option>");
                                        $County.html("<option value=''>请选择区县</option>");
                                    });
                                    $County.append(CountyData.join(''));
                                }
                            }).fail(function (xhr, textStatus, err) {
                                popWrap.alert({content:"省份获取失败",autoClose:false});
                            });
                        });
                        $City.trigger("change");
                        if(CountyId)
                        $("option[value="+CountyId+"]",$County).attr("selected",true);
                        //保存地址
                        saveAddress($dom2);
                        function saveAddress($dom2){
                            $("#saveAddress",$dom2).on("click",function(){
                                var __num = 0;
                                $("input,select",$dom2).each(function(v,k){
                                    var _validate = $(k).attr("validate"),
                                        tipTxt = $(k).parents("dl").children("dt").text(),
                                        val = $(k).val();
                                    if(val == ""){
                                        ++__num;
                                        popWrap.alert({content:tipTxt + "不能为空",autoClose:800});
                                        $(k).focus();
                                        return false;
                                    }else if(typeof _validate !== "undefined"){
                                        if(!validate[_validate](val)){
                                            ++__num;
                                            popWrap.alert({content:tipTxt + "格式不正确",autoClose:800});
                                            $(k).focus();
                                            return false;
                                        }
                                    }
                                });
                                
                                if($addressDetails.val() == ""){
                                    $addressDetails.focus();
                                    popWrap.alert({content:  "详细不能为空",autoClose:800});
                                    return false;
                                }else if(__num == 0){
                                    ajaxLoading.open();
                                    $.ajax({
                                        url:  _CONFIG[__webState].AJAX_URL+"/api/UserReceivingList/InsertReceiving",
                                        type: "post",
                                        dataType: "json",
                                        data: {
                                        	sysNo:_obj_.sysNo,
                                            CitySysNo: $City.val(),
                                            ProvinceSysNo: $Province.val(),
                                            DistrictSysNo: $County.val(),
                                            CompleteAddress: $addressDetails.val(),
                                            IsDefault: false,
                                            ReceivingName: $addressee.val(),
                                            MobilePhone:$mobile.val()
                                        }
                                    }).done( function (data) {
                                        ajaxLoading.remove();
                                        if(data.Code ==0){
                                            popWrap.alert({content:"添加成功",autoClose:800});
                                            getList();
                                            _this_.back($("#saveAddress",$dom2));
                                        }else{
                                            popWrap.alert({content:data.Message,autoClose:800});
                                        }
                                    }).fail(function (xhr, textStatus, err) {
                                        ajaxLoading.remove();
                                        popWrap.alert({content: "添加失败",autoClose:false});
                                    });
                                }
                            });
                        }

                    }});
                        
                }else{
                    popWrap.alert({content:data.Message,autoClose:false});
                }
            }).fail(function (xhr, textStatus, err) {   
                popWrap.alert({content:"访问异常，正在跳转至首页",autoClose:false});
                setTimeout(function(){
                    window.location.href =  _CONFIG[__webState].homePage_URL;
                },1000);
            }).always(function(){
                ajaxLoading.remove();
            })
       };
       getList();
        
        
        
    }})
}
